<?php

require_once( 'flexical/service/system.php' );

class Flexical_Service_Lock
{
	private $name;
	private $system;

	public function __construct( $name )
	{
		$this->name = $name;
		$this->system = new Flexical_Service_System();
	}

	private function get_lock_file()
	{
		return $this->system->get_tmp_dir() . DIRECTORY_SEPARATOR . 'locks' . DIRECTORY_SEPARATOR . $this->name;
	}

	public function lock()
	{
		while ( ! $this->acquire_lock() )
		{
			sleep( 1 );
		}
	}

	public function unlock()
	{
		$this->release_lock();
	}

	public function try_lock( $seconds )
	{
		while ( true )
		{
			if ( $this->acquire_lock() )
			{
				return true;
			}

			if ( $seconds > 0 )
			{
				sleep( 1 );
				$seconds--;
			}

			else
			{
				break;
			}
		}

		return false;
	}

	private function acquire_lock()
	{
		if ( file_exists( $this->get_lock_file() ) )
		{
			return false;
		}

		$handle = fopen( $this->get_lock_file(), 'w' );
		fclose( $handle );

		return true;
	}

	private function release_lock()
	{
		unlink( $this->get_lock_file() );
	}
}

?>
